local skynet = require "skynet"
local protocol = require "protocol"
local mongo_helper = require "mongo_helper"
local bson = require "bson"
local agent_helper = require "agent_helper"

local CMD = {}

local function on_login_req(packet, agent_source)
	print("packet", packet)
	local client = mongo_helper.get_client()
	local query = {account_name = packet.username, password = packet.password}
	local queryRet = client.birdgame.account:findOne(query)
	if queryRet ~= bson.encode{} then 
		agent_helper.send_data(agent_source, protocol.id.pid_login_ack, {result = "ok"})
	else 
		agent_helper.send_data(agent_source, protocol.id.pid_login_ack, {result = "username or password wrong"})
	end
	print ("loginReq, username:"..packet.username..",password:"..packet.password)

end

local function on_register_req(packet, agent_source)

end

function CMD.on_packet( protoid, packet, agent_source )
	if protoid == protocol.id.pid_login_req then
		on_login_req(packet, agent_source)
	elseif protoid == protocol.id.pid_register_req then
		on_register_req(packet, agent_source)
	end
end

function CMD.init(protoInstance, mongoInstance)
	protocol.instance = protoInstance
	mongo_helper.instance = mongoInstance

	protocol.add_handler(protocol.id.pid_login_req, skynet.self())
	protocol.add_handler(protocol.id.pid_register_req, skynet.self())
end

skynet.start(function()
	skynet.dispatch("lua", function(session, source, cmd, ...)
		local f = CMD[cmd]
		assert(f)
		skynet.ret(skynet.pack(f(...)))
	end)
end)
